package com.xingxue.logistics.controller.sys;


import com.xingxue.logistics.common.annotation.NeedLogin;
import com.xingxue.logistics.common.annotation.UnLogin;
import com.xingxue.logistics.common.utils.CodeImage;
import com.xingxue.logistics.common.vo.Constant;
import com.xingxue.logistics.common.vo.RestResult;
import com.xingxue.logistics.common.dto.SysUser;
import com.xingxue.logistics.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import static javax.swing.UIManager.get;

@RestController
@RequestMapping("")
@UnLogin
//Swagger的 @Api写在Controller上，用于描述一个Controller类
@Api(description = "登陆、退出、验证码等")
public class AuthController {

    @Autowired
    UserService userService;

    //Swagger的 @ApiOperation注解用于描述一个controller方法，tags属性会新开一个页签
    @ApiOperation( value="获取登陆验证码",notes = "不需要参数，将返回一个验证码图片，验证码在30分钟以内有效")
    @GetMapping("imgcode")
    public void loadImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Object[] obj = CodeImage.createCodeImage();
        String codeStr = (String) obj[0];
        BufferedImage codeImage = (BufferedImage) obj[1];
        session.setAttribute(Constant.USER_LOGIN_CODE_IMG_KEY,codeStr);

        response.setContentType("image/jpeg");
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);

        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(codeImage,"JPEG",outputStream);
        outputStream.flush();
        outputStream.close();
    }

    @ApiOperation(value = "判断是否已经登陆",notes = "状态码200为已经登陆，401为未登录")
    @GetMapping("islogin")
    public ResponseEntity isLogin(HttpServletRequest request){
        SysUser currentUser = (SysUser) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        if(currentUser==null){
            return new ResponseEntity(null,HttpStatus.UNAUTHORIZED);
        }
        return ResponseEntity.ok(new RestResult<SysUser>(true,null,currentUser));
    }



    @PostMapping("login")
    @ApiOperation(value = "登陆操作",notes = "进行登陆")
    public ResponseEntity<RestResult> doLogin(@RequestParam @ApiParam(value = "账号",required = true) String account,
                                              @RequestParam @ApiParam(value = "密码",required = true) String pwd,
                                              @RequestParam @ApiParam(value = "验证码",required = true) String imgCode,
                                               HttpServletRequest request){
        //校验验证码
        String sessionImgCode = (String) request.getSession().getAttribute(Constant.USER_LOGIN_CODE_IMG_KEY);
       /* //TODO 开发阶段屏蔽验证码，发布生产请放开
       if(sessionImgCode == null){
            return new ResponseEntity<RestResult>(new RestResult(false,"验证码错误",null), HttpStatus.UNAUTHORIZED);
        }
        request.getSession().removeAttribute(Constant.USER_LOGIN_CODE_IMG_KEY);
        if(!imgCode.toLowerCase().equals(sessionImgCode.toLowerCase())){
            return new ResponseEntity<RestResult>(new RestResult(false,"验证码错误",null), HttpStatus.UNAUTHORIZED);
        }*/
        //用户名密码，登陆逻辑
        RestResult<SysUser> result = userService.doLogin(account, pwd);
        if(result.isSuccess()){
            SysUser user = result.getData();
            request.getSession().setAttribute(Constant.USER_SESSION_KEY,user);
            return ResponseEntity.ok(result);
        }
        return new ResponseEntity<RestResult>(result, HttpStatus.UNAUTHORIZED);
    }


    @PostMapping("logOut")
    @NeedLogin
    @ApiOperation("退出登陆")
    public ResponseEntity logOut(HttpServletRequest request){
        request.getSession().removeAttribute(Constant.USER_SESSION_KEY);
        return new ResponseEntity(null, HttpStatus.UNAUTHORIZED);
    }

}
